

function addr_Joining(...array) {
  let url = "/"
  for (let i=0;i<array.length;i++) {
	url += array[i]
  }
  return url
}

function pupmessage(mesg) {
  let tol = document.getElementById("statUpdate")
  let msg = tol.firstChild.firstChild.firstChild.nextSibling
  msg.innerText = mesg
  let btn = document.createElement("button")
  btn.dataset.bsToggle = "modal"
  btn.dataset.bsTarget = "#statUpdate"
  btn.type = "button"
  btn.class = "btn btn-none"
  document.body.appendChild(btn)
  btn.click()
  document.body.removeChild(btn)
}

function anonymous(value, type, id) {
  let mesg = "", suffx = "", murl = ""
  switch (value) {
	case 1:
	  murl  = "api/cover/v3/"
	  suffx = "png"
	  mesg  = "封面文件必须为png格式"
	  break
	case 2:
	  murl = "api/update_barrage_comments/"
	  switch (type) {
		case "1":
		  suffx = "xml"
		  mesg  = "弹幕文件必须为xml可解析格式，B站为标准"
		  break
		case "2":
		  pupmessage("暂不支持")
		  return
	  }
	  break
	case 3:
	  murl = "api/subtitle_lyrics/v2/"
	  switch (type) {
		case "1":
		  suffx = "vtt"
		  mesg  = "字幕文件必须为vtt格式"
		  break
		case "2":
		  suffx = "lrc"
		  mesg  = "歌词文件必须为lrc格式"
		  break
	  }
	  break
  }
  update_file(id, mesg, murl, suffx)
}

function update_file(id, mesg, url, sufx) {
  let file = document.createElement("input")
  file.addEventListener("change", function() {
    let myfile = file.files[0]
    let f = myfile["name"].split(".")
    if (f[f.length-1] == sufx) {
	  let mfiles = new FormData()
	  mfiles.append("file", myfile)
	  mfiles.append("id", id)
	  axios.post(addr_Joining(url), mfiles, {
	    headers: {
		  'Content-Type': 'multipart/form-data'
	    }
	  }).then((response)=> {
	    console.log(response.data)
	  }).catch(error=>{
	    console.log(error)
	  })
    }else{
	  pupmessage(mesg)
    }
  })
  file.type = "file"
  file.accept = "." + sufx
  file.style.display = "none"
  file.name = "Files"
  file.click()
}

function ffmpeg_conversion(parent, id) {
  let but = parent.getElementsByClassName("btn btn-primary btn-sm")[0]
  but.disabled = true
  let text = but.textContent
  let iddt = new FormData()
  iddt.append("id", id)
  axios.post(addr_Joining("api/ffmpeg/v1/"), iddt).then((response)=> {
	var ws
	ws = new WebSocket("ws://" + window.location.hostname + ":" + window.location.port + "/api/ffmpeg/v1/")
	ws.onopen = function(evt) {
	  ws.send(id)
	  but.innerText = "连接"
	}
	ws.onclose = function(evt) {
	  ws = null
	  but.disabled = false
	  but.innerText = text
	}
	ws.onmessage = function(evt) {
	  but.innerText = evt.data + "%"
	}
	ws.onerror = function(evt) {
	  ws.close()
	}
  }).catch(
	error=>{
	  console.log(error)
  }) 
}

function creat_button(div_obj, class_name, class_call, class_text) {
  div_obj.className = "col-auto"
  let button = document.createElement("button")
  button.className = class_name
  button.type = "button"
  button.onclick = class_call
  button.innerText = class_text
  div_obj.appendChild(button)
  return button
}

function creat_allvice(type, id) {
  let div = document.createElement("div")
  div.className = "row mb-3"
  let div1 = document.createElement("div")
  let div2 = document.createElement("div")
  let div3 = document.createElement("div")
  let div4 = document.createElement("div")
  let button_update_cover      = creat_button(div1, "btn btn-secondary btn-sm", function () { anonymous(1, type, id) }, "上传封面")
  let button_barrage_comments  = creat_button(div2, "btn btn-secondary btn-sm", function () { anonymous(2, type, id) }, "") 
  let button_Subtitle_lyrics   = creat_button(div3, "btn btn-secondary btn-sm", function () { anonymous(3, type, id) }, "") 
  let button_ffmpeg_conversion = creat_button(div4, "btn btn-primary btn-sm",   function () { ffmpeg_conversion(div4, id) }, "") 
  switch (type) {
	case "1":
	  button_barrage_comments.innerText  = "上传弹幕"
	  button_Subtitle_lyrics.innerText   = "上传字幕"
	  button_ffmpeg_conversion.innerText = "mp4-h264转换"
	  break
	case "2":
	  button_barrage_comments.innerText  = "上传评论"
	  button_Subtitle_lyrics.innerText   = "上传歌词"
	  button_ffmpeg_conversion.innerText = "mp3转换"
	  break
  }
  div.appendChild(div1)
  div.appendChild(div2)
  div.appendChild(div3)
  div.appendChild(div4)
  return div
}

function creatplayer_mp3(filename, suffx, id, type) {
  let parent = document.getElementById('mydiv')
  parent.appendChild(document.createElement("br"))
  parent.appendChild(creat_allvice(type, id))
  let play = document.getElementById('player')
  let img = document.createElement("img")
  parent.className = "text-center"
  img.src = "../images/jjy.jpg"
  parent.insertBefore(img, parent.firstElementChild)
  window.mplay = new APlayer({
    container: play,
    lrcType: 3,
    audio: {
      name: filename.split("-")[0],
      artist: filename.split("-")[1],
      url: addr_Joining("api/download?name=", filename, "&id=", id),
      cover: addr_Joining("api/cover/v3/?id=", id),
      lrc: addr_Joining("api/subtitle_lyrics/v2/?id=", id)
    }
  });
}

function creatplayer_mp4(filename, suffx, id, type) {
  let parent = document.getElementById('mydiv')
  let v = creat_allvice(type, id)
  parent.appendChild(document.createElement("br"))
  parent.appendChild(v)
  window.mplay = new DPlayer({
    container: document.getElementById('player'),
    preload: 'none',
    lang: "zh-cn",
    video: {
      url: addr_Joining("api/download?id=", id, "&name=", filename),
      type: suffx,
      pic: addr_Joining("api/cover/v3/?id=", id),
    },
    danmaku: {
      id: id,
      api: addr_Joining("api/barrage_comments/"),
      user: localStorage.getItem("user"),
    },
  });
}

function creatplayer_png(filename, suffx, id, type) {
	let parent = document.getElementById('player')
	let img = document.createElement("img")
	img.classList.add('img-fluid')
	img.src = "/api/download?id=" + id + "&name=" + filename
	parent.className = "text-center"
	parent.appendChild(img)
}

function creatplayer_file(filename, suffx, id, type) {
	let parent = document.getElementById('player')
	let img = document.createElement("img")
	parent.className = "text-center"
	img.src = "../images/file.ico"
	parent.appendChild(img)
}

function getQueryVariable(variable){
  let query = window.location.search.substring(1);
  let vars = query.split("&");
  for (let i=0;i<vars.length;i++) {
    let pair = vars[i].split("=");
    if(pair[0] == variable){return pair[1];}}
  return(false);
}

var app = Vue.createApp({
	data(){
		return {
      mname: "",
    	mtime: "",
    	mid:   "",
    	mtype: "",
    	suffx: "",
		}
	},
	created() {
    this.receiveMessage(getQueryVariable("id"), "watch")
	},
	methods:{
		receiveMessage(key, url) {
	    axios.get(addr_Joining("api/", url), {
	      params: {
	        id: key
	      }
	    }).then(
	      res=>{
	        if (url == "watch") {
		        this.mname = res.data['msg']["name"]
		        this.mtime = res.data['msg']["time"]
		        this.mid   = res.data['msg']["id"]
		        this.mtype = res.data['msg']["type"]
		        this.suffx = res.data['msg']["suffix"]   	
		        switch (this.mtype) {
		        	case "1":
		        		creatplayer_mp4(this.mname, this.suffx, this.mid, this.mtype)
		        		break
		        	case "2":
		        		creatplayer_mp3(this.mname, this.suffx, this.mid, this.mtype)
		        		break
		        	case "3":
		        		creatplayer_png(this.mname, this.suffx, this.mid, this.mtype)
		        		break
		        	case "4":
		        		creatplayer_file(this.mname, this.suffx, this.mid, this.mtype)
		        		break
		        }		
	        }
	        console.log(res.data['msg'])
	      }
	    ).catch(
	      error=>{
	        console.log(error)
	      }
	    )
		},
		on_refresh(){
			this.receiveMessage(this.mid, "watch")
		},
		on_delete(){
			this.receiveMessage(this.mid, "delete")
			//window.location.href="../"
			history.go(-1)
		},
		on_downloadClick(row) {
			let address = addr_Joining("api/download?id=", row, "&name=", this.mname)
			console.log(address)
			let a = document.createElement('a')
			a.setAttribute('href', address)
			document.body.appendChild(a)
			a.click()
			document.body.removeChild(a)
		},
		on_updateClick(row) {
			let address = "/update?id=" + row 
			let a = document.createElement('a')
			a.setAttribute('href', address)
			document.body.appendChild(a)
			a.click()
		},
		on_ArtEditModalFunBlur(event) {
			console.log(event.path[0].outerText)
		}
	},
 })

app.mount('#app')